﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

using Authentication.User;
using Common;

namespace BuyRequest
{
    partial class ViewBuyRequest : PortalModuleBase, IActionable
    {
        #region Private Members
        private int loginUserType
        {
            get
            {
                if (Session["loginUserType"] == null) return 0;
                return (int)Session["loginUserType"];
            }
        }
        private bool fAdminMode = false;  // Admin or owner login
        private string SQL_LastBuyRequest()
        {
            string condStr = "";
            string SQLCmd =
                "SELECT TOP " + Common.systemSettings.sysDefaultTopNewBuyRequestNum + " a.requestId,a.Name1 AS name,c.description1 AS status," +
                " a.RegisterDate,ISNULL(a.lastModifyDate,'') AS lastModifyDate,ISNULL(a.expireDate,'') AS expireDate," +
                " a.registerBy AS buyerId," +
                " CASE WHEN b.companyName1 IS NULL THEN b.fullName ELSE b.companyName1 END AS buyerName " +
                " FROM dbo.tm_buy_request a INNER JOIN  tm_users b ON a.RegisterBy = b.userId" +
                " INNER JOIN tm_buyStatus c ON a.status = c.statusCode " +
                " WHERE (a.expireDate IS NULL OR a.expireDate > '" + sysLibs.ConvertToSQLDateString(DateTime.Now) + "')";

            //Combine all to make a valid query string
            SQLCmd += (condStr == "" ? "" : " AND " + condStr);
            SQLCmd += " ORDER BY registerDate DESC";
            return SQLCmd;
        }
        private string SQL_BuyRequestBySyscode(int syscodeID)
        {
            //int maxCount = (Common.systemSettings.sysTypicalProductMaxRow * Common.systemSettings.sysTypicalProductPerRow);
            string SQLCmd =
                "SELECT a.requestId,a.Name1 AS name,d.description1 AS status,a.processNotes," +
                " a.registerDate,ISNULL(a.expireDate,'') AS expireDate,ISNULL(a.lastModifyDate,'') AS lastModifyDate," +
                " a.registerBy AS buyerId," +
                " CASE WHEN b.companyName1 IS NULL THEN b.fullName ELSE b.companyName1 END AS buyerName" +
                //",ISNULL(a.clickCounter,0)AS clickCounter, ISNULL(b.clickCounter,0)AS clickCounterUser ," +
                " FROM dbo.tm_buy_request a INNER JOIN  tm_users b ON a.RegisterBy = b.userId " +
                " INNER JOIN  tm_buy_request_syscodes c ON c.requestId = a.requestId " +
                " INNER JOIN tm_buyStatus d ON a.status = d.statusCode" +
                " WHERE (a.status = '" + Common.consts.constStatusENABLE + "') " +
                " AND (c.syscodeId = " + syscodeID.ToString() + ") AND (a.expireDate IS NULL OR a.expireDate > '" + sysLibs.ConvertToSQLDateString(DateTime.Now) + "')" +
                " ORDER BY registerDate DESC";
            return SQLCmd; 
        }
        private string SQL_BuyRequestByUser()
        {
            string SQLCmd =
                "SELECT a.requestId,a.Name1 AS name," +
                " a.RegisterDate,'' AS lastModiFyDate,'' AS expireDate ,'' AS status," +
                " a.registerBy AS sellerId," +
                " CASE WHEN b.companyName1 IS NULL THEN b.fullName ELSE b.companyName1 END AS userName,a.processNotes" +
                " FROM tm_buy_request a INNER JOIN  tm_users b ON a.RegisterBy = b.userId " +
                " WHERE (a.status = '" + Common.consts.constStatusENABLE + "') " +
                " AND a.registerBy = " + appLibs.GetOwnerIdFromStore(PortalId) + " AND (a.expireDate IS NULL OR a.expireDate > '" + sysLibs.ConvertToSQLDateString(DateTime.Now) + "')" +
                " ORDER BY registerDate DESC";
            return SQLCmd;
        }
        private void ShowRequest(string SQLCmd,string title,bool isAdminMode,bool isLogin)
        {
                BuyRequestList.SetTableTitle(controls_buyRequestList.columnName.name, title);
                Common.sysLibs.ShowDebugMsg(lblDebugMsg, SQLCmd);

                BuyRequestList.Visible = true;
                BuyRequestList.SQLCmd = SQLCmd;
                BuyRequestList.RequestData();

                //Only visible the list when there is some search result
                pnlBuyRequestList.Visible = (BuyRequestList.SearchRecordCount > 0);

                //Only visible the SetStatus panel for Admin / Owner
                BuyRequestList.SetBottomPannelVisible(fAdminMode);
                BuyRequestList.SetExportButtonVisible = fAdminMode;
                BuyRequestList.SetDeleteButtonVisible = fAdminMode;
                BuyRequestList.SetCheckAllVisible = UserId > 0;

                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName._check, isLogin);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName.name, true);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName._contact, true);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName.registerDate, true);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName.lastModifyDate, isAdminMode);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName.expireDate, isAdminMode);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName.status, false);

                bool bottomVisible = isLogin && BuyRequestList.SearchRecordCount > 0;
                BuyRequestList.SetBottomPannelVisible(bottomVisible);
                BuyRequestList.SetCheckAllVisible = true;
                BuyRequestList.SetStatusListVisible(false);
                //Only visible the SetStatus panel when 
                // - Admin mode
                // - There is some search result
                BuyRequestList.SetDeleteButtonVisible = isAdminMode;
                BuyRequestList.SetExportButtonVisible = isAdminMode;
                return;
        }
        
        private bool AddToMySpace(GridView gvItemList)
        {
            int buyRequestId;
            try
            {
                for (int i = 0; i < gvItemList.Rows.Count; i++)
                {
                    CheckBox ck = (CheckBox)gvItemList.Rows[i].FindControl("chkItem");

                    if (!ck.Checked) continue;
                    buyRequestId = Null.NullInteger;
                    int.TryParse(((Label)gvItemList.Rows[i].FindControl("lblRequestId")).Text, out buyRequestId);
                    if (!appLibs.InsertToUserProfile(UserId, buyRequestId, consts.constProfileBuyRequest))
                    {
                        Common.sysLibs.ShowNotice(lblMessage, "Thêm vào <Kho của tôi> gặp lỗi", false);
                        return false;
                    }
                }
                Common.sysLibs.ShowNotice(lblMessage, "Đã thêm vào [Kho của tôi]", false);
            }
            catch (Exception exc)
            {
                Common.sysLibs.ShowNotice(lblMessage, exc.ToString(), true);
                return false;
            }
            return true;
        }
        #endregion

        #region Public Methods
        #endregion

        #region Optional Interfaces

        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        #endregion

        #region Event Handlers
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            int sysCodeId = 0;
            try
            {
                lblMessage.Visible = false;
                BuyRequestList.btnProcessText = "Thêm vào kho";
                BuyRequestList.curPortalId = PortalId;
                BuyRequestList.PageSize = Common.systemSettings.sysNoOfSearchResultPerPage;
                
                //Set implemented function to process Status button click
                BuyRequestList.ProcessSelectedFunc = AddToMySpace;
                BuyRequestList.SetStatusListVisible(false);

                //Check if admin mode 
                fAdminMode = false;
                if (UserId > 0)  // Log-in
                    fAdminMode = (sysLibs.bitIsOn(loginUserType, consts.constSYSBitPos) ||
                                  sysLibs.bitIsOn(loginUserType, consts.constPRMBitPos));
                if (Request["syscodeId"] != null)
                {
                    sysCodeId = 0; int.TryParse(Request["syscodeId"].ToString(), out sysCodeId);
                }
                //If load the first time
                if (!Page.IsPostBack)
                {
                    //Show buy request for store (portal>0)
                    if (PortalId > 0)
                    {
                        ShowRequest(SQL_BuyRequestByUser(), "Yêu cầu",fAdminMode,UserId>0);
                        return;
                    }
                    if (sysCodeId <= 0)
                    {
                        ShowRequest(SQL_LastBuyRequest(), "Yêu cầu",fAdminMode,UserId>0);
                        this.Parent.Parent.Parent.Visible = pnlBuyRequestList.Visible;
                     }
                     else ShowRequest(SQL_BuyRequestBySyscode(sysCodeId), "Yêu cầu", fAdminMode, UserId > 0);  
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        #endregion
     
}
}

